package com.hst.web.auth.util;

import cn.hutool.core.util.StrUtil;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.web.auth.po.LoginRequest;
import com.hst.web.auth.po.User;
import com.hst.web.sys.entity.TUser;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import sun.rmi.runtime.Log;

import javax.validation.Valid;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 登录工具类
 *
 * @author Ding Ye
 * @date 2022/4/19
 */
public class LoginUtil {

	public static final Map<String, String> CAPTCHA_CACHE = new LinkedHashMap<String, String>() {
		@Override
		protected boolean removeEldestEntry(Map.Entry<String, String> pEldest) {
			return size() > 200;
		}
	};

	/***
	 * 校验验证码
	 * @param loginVo
	 **/
	@SneakyThrows
	public static void checkCode(@Valid LoginRequest loginVo) {
		String code = loginVo.getCaptcha();
		String randomStr = loginVo.getRandomStr();
		if (StrUtil.isBlank(code) || StrUtil.isBlank(randomStr)) {
			throw new Exception("验证码不能为空");
		}
		String codeCache = CAPTCHA_CACHE.get(randomStr);
		if(StringUtils.isBlank(codeCache)) {
			throw new Exception("随机码不合法");
		}
		if (!StringUtils.equals(code, codeCache)) {
			throw new Exception("验证码不合法");
		}
	}
}
